﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace pygs.Messaging.Transport
{
    public class FileTransport : CustomTransport
    {
        protected FileTransporters transporters { get; private set; }

        public string FileName { get; protected set; }

        protected override void InitilizeComponent()
        {
            base.InitilizeComponent();
            transporters = new FileTransporters();
            FileTransportersRegistration.RegisterTransporters(transporters);
        }

        protected override void FinalizeComponent()
        {
            base.FinalizeComponent();
        }

        public FileTransport(string FileName)
            : base()
        {
            this.FileName = FileName;
        }

        public FileTransport()
            : base()
        {
        }       

        public override void AssignParams(ComponentParams componentParams)
        {
            this.FileName = componentParams.ParamAsString("FileName");
        }

        protected StreamWriter Writer { get; private set; }

        protected StreamWriter GetWriter()
        {
            if (Writer == null)
            {
                string fn = FileName;
                if (fn == "")
                    fn = "track.txt";
                Writer = File.CreateText(fn);
                Writer.AutoFlush = true;
            }
            return Writer;
        }

        public override bool Send(List<Message> list, out SendingResult result)
        {
            bool success = true;
            result = new SendingResult();
            foreach (var message in list)
            {
                var transporter = transporters.GetTransporter(message);
                try
                {
                    if (transporter.Send(message, GetWriter()))
                    {
                        result.AddSended(message);
                    }
                    else
                    {
                        success = false;
                        result.AddFailed(message);
                    }
                }
                catch (SendingError e)
                {
                    success = false;
                    result.AddFailed(message);
                    result.AddError(e);
                };
            }
            return success;
        }
    }
}
